package cn.lbd.datastructure;

import java.awt.*;

/**
 * 数组形式顺序存储二叉树
 * **/
public class ArrayBinTree {
    private int[] arr;

    public ArrayBinTree(int[] arr) {
        this.arr = arr;
    }

    public void preOrder() {
        preOrder(0);
    }

    public void preOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("二叉树数组为空");
        }
        //根
        System.out.print(arr[index]);
        if (index * 2 + 1 < arr.length) {
            preOrder(index * 2 + 1);
        }
        if (index * 2 + 2 < arr.length) {
            preOrder(index * 2 + 2);
        }
    }

    public void infixOrder() {
        infixOrder(0);
    }

    public void infixOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("二叉树数组为空");
        }
        //根
        if (index * 2 + 1 < arr.length) {
            infixOrder(index * 2 + 1);
        }
        System.out.print(arr[index]);
        if (index * 2 + 2 < arr.length) {
            infixOrder(index * 2 + 2);
        }
    }

    public void postOrder() {
        postOrder(0);
    }

    public void postOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("二叉树数组为空");
        }
        //根
        if (index * 2 + 1 < arr.length) {
            postOrder(index * 2 + 1);
        }
        if (index * 2 + 2 < arr.length) {
            postOrder(index * 2 + 2);
        }
        System.out.print(arr[index]);
    }
}

class ArrayBinTreeDemo{
    public static void main(String[] args) {
        int arr[] = new int[]{1,2,3,4,5,6,7};
        ArrayBinTree arrayBinTree =  new ArrayBinTree(arr);
        arrayBinTree.preOrder();
        System.out.println();
        arrayBinTree.infixOrder();
        System.out.println();
        arrayBinTree.postOrder();
    }
}
